/**
 * Copyright (c) 2020-2021, LiangHM 梁海明 (lhm_sunny@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfinal.poi;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.jfinal.plugin.activerecord.Record;

//导入暂时仅支持单sheet 有需求的程序员可自行扩展
public class PoiImporter {

	// 第一行不解析，为描述字段信息
	private String[] columns;
	private URL urlFile;
	private File file;

	public List<Record> xlsimport() {
		if (columns == null) {
			System.out.println("columns can not be null");
			return null;
		}
		if (file == null && urlFile == null) {
			System.out.println("file can not be null");
			return null;
		}
		List<Record> xlslist = new ArrayList<>();
		BufferedInputStream in = null;
		try {
			if (file != null) {
				in = new BufferedInputStream(new FileInputStream(file));
			} else {
				in = new BufferedInputStream(urlFile.openStream());
			}
			Workbook wb = null;
			wb = new XSSFWorkbook(in);
			in.close();
			wb.close();
			// 创建工作表sheet
			Sheet sheet = wb.getSheetAt(0);
			// 获取sheet中数据的行数
			int rows = sheet.getPhysicalNumberOfRows();
			System.out.println("total rows" + rows);
			// 第一行不要
			for (int i = 1; i < rows; i++) {
				Record r = new Record();
				for (int j = 0; j < columns.length; j++) {
					String column = columns[j];
					Cell cell = sheet.getRow(i).getCell(j);
					if (cell != null) {
						cell.setCellType(CellType.STRING);
						r.set(column, cell.getStringCellValue());
					} else {
						r.set(column, null);
					}
				}
				xlslist.add(r);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return xlslist;
	}

	public PoiImporter columns(String... columns) {
		this.columns = columns;
		return this;
	}

	public PoiImporter urlFile(URL urlFile) {
		this.urlFile = urlFile;
		return this;
	}

	public PoiImporter file(File file) {
		this.file = file;
		return this;
	}

}
